package com.longge.wechat.controller.web;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieController {

	//cookie方式点赞
	public void doPraise(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		Integer id  = Integer.parseInt(request.getParameter("id"));
		String cName = "cook"+id;
		String cValue = ""+id;
		Cookie cookie = new Cookie(cName, cValue);
		cookie.setMaxAge(365*24*3600);
		response.addCookie(cookie);
		
		//final ImageEntity imageEntity = imageServiceImpl.findImageById(id);
		 Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
		 int i = 0;
		 String rs = "";
	     if(cookies == null) {
	    	 rs = "点赞成功";
	    	 /*imageEntity.setPraiseCount(imageEntity.getPraiseCount()+1);
	    	 imageServiceImpl.updateImage(imageEntity);
	    	 if(imageEntity.getPraiseCount() == 2) {
	    		 new Thread(new Runnable(){
	    			 public void run(){
	    	            pressImageServiceImpl.addPressImage(imageEntity);
	    	         }
	    	      }).start();
			 }*/
	     }else {
	    	 for(Cookie entity : cookies){
				  if(cName.equals(entity.getName()) && cValue.equals(entity.getValue())) {
					  rs = "已点赞";
					break;
				  }else {
					i++;
				  }
				  if(i == cookies.length) {
					  rs = "点赞成功";
					  /*imageEntity.setPraiseCount(imageEntity.getPraiseCount()+1);
					  imageServiceImpl.updateImage(imageEntity);
					  if(imageEntity.getPraiseCount() == 2) {
			    		 new Thread(new Runnable(){
			    			 public void run(){
			    	            pressImageServiceImpl.addPressImage(imageEntity);
			    	         }
			    	      }).start();
					  }*/
				  }
	    	 }
	     }
		out.println(rs);
		out.flush();
		out.close();
	}
}
